package io.gitee.kotle.android.adapter

import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers

open class RecyclerViewPagingAdapter<Data : Any>(
    private val areItemTheSame: ((old: Data?, new: Data?) -> Boolean)? = null,/*是否是同一组数据*/
    private val areContentsTheSame: ((old: Data?, new: Data?) -> Boolean)? = null,/*是否内容相同*/
    mainDispatcher: CoroutineDispatcher = Dispatchers.Main.immediate,
    workerDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : PagingDataAdapter<Data, RecyclerViewHolder<Data, *>>(object : DiffUtil.ItemCallback<Data>() {
    override fun areItemsTheSame(oldItem: Data, newItem: Data): Boolean {
        return areItemTheSame?.invoke(oldItem, newItem) ?: (oldItem == newItem)
    }

    override fun areContentsTheSame(oldItem: Data, newItem: Data): Boolean {
        return areContentsTheSame?.invoke(oldItem, newItem) ?: false
    }

}, mainDispatcher, workerDispatcher), IRecyclerViewAdapter<Data> by DefaultRecyclerViewAdapterImpl() {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder<Data, *> {
        return onCreateRecyclerViewHolder(parent, viewType)
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder<Data, *>, position: Int) {

    }

    override fun onBindViewHolder(
        holder: RecyclerViewHolder<Data, *>,
        position: Int,
        payloads: MutableList<Any>
    ) {
        super.onBindViewHolder(holder, position, payloads)
        onBindRecyclerViewHolder(
            holder,
            position,
            payloads,
            itemCount - 1 == position,
            getItem(position)
        )
    }


    override fun getItemViewType(position: Int): Int {
        return getRecyclerViewItemViewType(position, getItem(position))
    }

    override fun onViewAttachedToWindow(holder: RecyclerViewHolder<Data, *>) {
        super.onViewAttachedToWindow(holder)
        onRecyclerViewHolderAttachedToWindow(holder)
    }

    override fun onViewDetachedFromWindow(holder: RecyclerViewHolder<Data, *>) {
        super.onViewDetachedFromWindow(holder)
        onRecyclerViewHolderDetachedFromWindow(holder)
    }

    override fun onViewRecycled(holder: RecyclerViewHolder<Data, *>) {
        super.onViewRecycled(holder)
        onRecyclerViewHolderRecycled(holder)
    }

    override fun onFailedToRecycleView(holder: RecyclerViewHolder<Data, *>): Boolean {
        onRecyclerViewHolderFailedToRecycleView(holder)
        return super.onFailedToRecycleView(holder)
    }

    override fun getItemData(position: Int): Data? {
        return getItem(position)
    }
}